<?php
namespace backend\models;

use backend\models\BackendUser;
use yii\base\Model;
use Yii;
use yii\helpers\VarDumper;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $username;
    public $email;
    public $password_hash;
    public $repeatpassword;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
//            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'required'],
//            ['username', 'unique', 'targetClass' => '\backend\models\BackendUser', 'message' => 'This username has already been taken.'],
//            ['username', 'string', 'min' => 2, 'max' => 255],
//
//            ['email', 'filter', 'filter' => 'trim'],
//            ['email', 'required'],
//            ['email', 'email'],
//            ['email', 'string', 'max' => 255],
//            ['email', 'unique', 'targetClass' => '\backend\models\BackendUser', 'message' => 'This email address has already been taken.'],
            ['repeatpassword','compare','compareAttribute'=>'password_hash','message'=>'两次输入的密码不一致！'],
            ['password_hash', 'required'],
            ['password_hash', 'string', 'min' => 6],
        ];
    }

    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'password_hash' => '密码',
            'repeatpassword' => '重复密码',
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if ($this->validate()) {//echo '111';exit;
            $user = new BackendUser();
            $user->username = $this->username;
//            $user->email = $this->email;
            $user->setPassword($this->password_hash);
            $user->generateAuthKey();
//            $user->save();VarDumper::dump($user->errors);exit;
            if ($user->save()) {
                return $user;
            }
        }

        return null;
    }
}
